// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database();
const _ = db.command;

// 云函数入口函数
exports.main = async (event, context) => {
  try {
    const { 
      searchType, 
      searchKeyword, 
      page = 1, 
      pageSize = 10 
    } = event;
    
    if (!searchKeyword) {
      return {
        success: false,
        message: '搜索关键词不能为空'
      };
    }
    
    const skip = (page - 1) * pageSize;
    
    // 构建查询条件
    let query = {
        status:true
    };
    
    // 根据搜索类型构建不同的查询条件
    switch (searchType) {
      case 'ip':
        query['ipName'] = db.RegExp({
          regexp: searchKeyword,
          options: 'i'
        });
        break;
      case 'series':
        query['seriesName'] = db.RegExp({
          regexp: searchKeyword,
          options: 'i'
        });
        break;
      case 'product':
        query['productName'] = db.RegExp({
          regexp: searchKeyword,
          options: 'i'
        });
        break;
      case 'name':
      default:
        query.goodsName = db.RegExp({
          regexp: searchKeyword,
          options: 'i'
        });
        break;
    }
    // 执行查询
    const goodsResult = await db.collection('blindbox_goods')
      .where(query)
      .orderBy('createTime', 'desc')
      .skip(skip)
      .limit(pageSize)
      .get();
    
    // 获取总数量
    const countResult = await db.collection('blindbox_goods')
      .where(query)
      .count();
    
    return {
      success: true,
      data: goodsResult.data,
      total: countResult.total
    };
  } catch (e) {
    console.error('搜索商品失败', e);
    return {
      success: false,
      message: '搜索商品失败',
      error: e
    };
  }
};